package com.qingxin.sys.verifier;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.FromXmlRuleSet;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * XML解析器
 * 
 * @author JiWangli
 */
public class XMLDigester extends Digester {
	
	private File rootFilepath;
	private File rulesFile;
	
	
	public XMLDigester() {
	}
	
	
	public XMLDigester(File rulesFile) throws IOException {
		setRulesFile(rulesFile);
		setValidating(false);
		setUseContextClassLoader(true);
	}


	public XMLDigester(URL rulesURL) throws IOException, URISyntaxException{
		setRulesFile(new File(rulesURL.toURI()));
		setValidating(false);
		setUseContextClassLoader(true);
	}
	
	
	@Override
	public Object parse(File file) throws IOException, SAXException {
		this.rootFilepath = file.getParentFile();
		return super.parse(file);
	}
	
	
	@Override
	public Object parse(URL url) throws IOException, SAXException {
		try {
			this.rootFilepath = (new File(url.toURI())).getParentFile();
		} catch (Exception e) {
		}
		return super.parse(url);
	}
	
	
	public File getRootFilepath() {
		return rootFilepath;
	}

	public void setRootFilepath(File rootFilepath) {
		this.rootFilepath = rootFilepath;
	}

	public File getRulesFile() {
		return rulesFile;
	}
	
	public void setRulesFile(File rulesFile) throws IOException {
		this.rulesFile = rulesFile;
		if(rulesFile != null){
			addRuleSet(new FromXmlRuleSet(new InputSource(new FileInputStream(this.rulesFile)), new XMLRuleSetParser()));
		}
	}
	
	
}
